package ThreadDemo;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 34255
 * Date: 2024-10-15
 * Time: 10:58
 */
public class Demo15 {
    public static int count = 0;
    public static void main(String[] args) throws InterruptedException {
        //多个线程对同一个变量就行操作，为了保证线程安全，需对线程进行加锁，且加的锁必须是同一个锁才能保证线程安全
        //才能互斥，保证必须执行完线线程里的加锁任务，操作系统才能进行线程调度
        Thread thread1 = new Thread(() -> {
            synchronized(Object.class){//锁对象
                for (int i = 0; i < 50000; i++) {
                    count++;
                }
            }
        });

        Thread thread2 = new Thread(() -> {
            synchronized(Object.class){//锁对象
                for (int i = 0; i < 50000; i++) {
                    count++;
                }
            }
        });

        thread1.start();
        thread2.start();
        thread1.join();//让main线程等待thread1的线程任务执行完毕，才能接受操作系统线程调度
        thread2.join();//让main线程等待thread2的线程任务执行完毕，才能接受操作系统线程调度

        System.out.println("count = " + count);
        //打印出0，代表其他线程还没开始执行任务，main主线程就提前结束
    }
}
